#!/usr/bin/perl -w


use strict;
use Data::Dumper;
use DBI;
use POSIX;
use IPC::ShareLite;
use Storable qw(freeze thaw);
use IPC::ShareLite qw( :lock );

my @ip;
my %result;
my %pid_task;
my $date=shift;
my $fork |= 10;
my $hash={};

foreach (1...169)
{
        push @ip,"192.168.1.$_";
}

my $share = IPC::ShareLite->new(
        -key     => 1981,
        -create  => 'yes',
        -destroy => 'no'
) or die $!;

$share->store(freeze($hash));

&main;

sub main
{
&my_fork;
&tosqlite;
}


sub my_fork
{
while ( my $task = shift @ip)
{
        if (scalar (keys %pid_task) >= $fork)
        {
        my $kid = wait;
        delete $pid_task{$kid};
        }

        if ( my $pid = fork )
        {
        $pid_task{$pid} = $task;
        } else {
                child_process($task);
                exit;
        }
}
while ( my $kid = wait )
{
        last if $kid < 0;
}

}

sub child_process {

my $ip = shift;

$share->lock( LOCK_EX );
$hash=thaw($share->fetch);
chomp (${$hash}{"$ip"}{"num"}=`ssh -o ConnectTimeout=10 $ip 'if [ -s "logs/access_log.$date.gz" ];then zcat logs/access_log.$date.gz | wc -l;else wc -l logs/access_log.$date;fi' | awk '{ print \$1 }'`);
chomp (${$hash}{"$ip"}{"wt"}=`/bin/egrep -A10 'IP=\"$ip\\b\"' ~/conf/hosts.cf | /bin/grep WMWeight | /bin/grep -Po '\"\\d+' | sed 's/\"//g'`);
$share->store(freeze($hash));
$share->unlock;
}

sub tosqlite
{
my $dbh=DBI->connect("dbi:SQLite:dbname=a.db","","",{RaiseError=>1,AutoCommit=>0});
if ( ! -s "a.db" )
{
my $sql="create table Wta( date DATE,ip CHAR(15),wt INT,acc_num VARCHAR(255),PRIMARY KEY (date,ip))";
$dbh->do($sql);
}
$hash=thaw($share->fetch);
my $sql="replace into Wta (date,ip,wt,acc_num) values (?,?,?,?)";
my $sth=$dbh->prepare($sql);
for my $ip (sort keys %{$hash})
{
   $sth->execute($date,$ip,${$hash}{"$ip"}{"wt"},${$hash}{"$ip"}{"num"});
}
$sth->finish;
$dbh->commit();
$sql="select date,ip,wt,acc_num from Wta";
my $dbconn=$dbh->prepare($sql);
$dbconn->execute();
$dbconn->dump_results();
$dbconn->finish();
$dbh->disconnect;
}

